package com.tju.resource.server.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.TbOutwardMapper;
import com.tju.resource.model.TbOutward;
import com.tju.resource.server.TbOutwardService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ClientParameters;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

import static com.tju.resource.tool.tool.QuickQuery.*;

@Service
public class TbOutwardServiceImpl implements TbOutwardService {

    @Autowired
    TbOutwardMapper mapper;

    @Override
    public Result<Object> getAll(ClientParameters params) {
        try {
            Page<TbOutward> page = new Page<>(params.getPage(), params.getLimit());
            IPage<TbOutward> iPage = mapper.getAll(page, params);
            List<TbOutward> records = iPage.getRecords();
            return ResultUtil.success(ResultEnum.SUCCESS, records, iPage.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, e.getMessage());
        }
    }

    @Override
    @Transactional
    public int add(TbOutward outward) {
        boolean exists = list(mapper, params().putOnce("supplier", outward.getSupplier())).size() > 0;

        if (!exists) {
            outward.setCreateTime(new Date());

            return mapper.insert(outward);
        } else {
            throw new ServiceException("对应的供应商名称已存在!");
        }
    }

    @Override
    @Transactional
    public int upd(TbOutward outward) {
        TbOutward ow = mapper.selectById(outward.getId());

        if (StringUtils.equals(outward.getSupplier(), ow.getSupplier())) {
            return mapper.updateById(outward);
        } else {
            boolean exists = list(mapper, params().putOnce("supplier", outward.getSupplier())).size() > 0;

            if (!exists) {
                return mapper.updateById(outward);
            } else {
                throw new ServiceException("对应的供应商名称已存在!");
            }
        }
    }

    @Override
    @Transactional
    public int del(Long oId) {
        return mapper.deleteById(oId);
    }

}
